<template>
    <div class="dashboard-container">
      <!-- 算法选择 -->
      <div class="section">
        <h2 class="section-title">算法选择</h2>
        <div class="algorithm-cards">
          <div class="algorithm-card" :class="{ active: selectedAlgorithm === 'cnn' }" @click="selectAlgorithm('cnn')">
            <div class="algorithm-icon">
              <el-icon><Monitor /></el-icon>
            </div>
            <div class="algorithm-content">
              <div class="algorithm-name">CNN</div>
              <div class="algorithm-desc">卷积神经网络</div>
            </div>
          </div>
          
          <div class="algorithm-card" :class="{ active: selectedAlgorithm === 'lstm' }" @click="selectAlgorithm('lstm')">
            <div class="algorithm-icon">
              <el-icon><Timer /></el-icon>
            </div>
            <div class="algorithm-content">
              <div class="algorithm-name">LSTM</div>
              <div class="algorithm-desc">时序特性</div>
            </div>
          </div>
          
          <div class="algorithm-card" :class="{ active: selectedAlgorithm === 'hybrid' }" @click="selectAlgorithm('hybrid')">
            <div class="algorithm-icon">
              <el-icon><DataAnalysis /></el-icon>
            </div>
            <div class="algorithm-content">
              <div class="algorithm-name">混合模型</div>
              <div class="algorithm-desc">CNN+LSTM</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 上传数据区 -->
      <div class="upload-section">
        <div class="upload-box">
          <div class="upload-icon">
            <el-icon><Upload /></el-icon>
          </div>
          <div class="upload-title">上传检测数据集</div>
          <div class="upload-desc">支持 CSV/PCAP/NetFlow 等格式上传</div>
          <div class="upload-desc">兼容 NSL-KDD、CIC/IDS2017 等主流公开数据集</div>
          
          <input 
            type="file" 
            ref="fileInput" 
            style="display: none" 
            accept=".csv,.pcap,.xls,.xlsx"
            @change="handleFileChange"
          />
          <el-button 
            type="primary" 
            class="upload-button" 
            @click="triggerFileUpload"
            :loading="uploading"
          >
            {{ uploading ? '正在上传...' : '选择文件上传' }}
          </el-button>
          
          <div v-if="selectedFile" class="selected-file">
            <el-icon><Document /></el-icon>
            <span>{{ selectedFile.name }}</span>
            <el-icon class="remove-icon" @click="clearSelectedFile"><Close /></el-icon>
          </div>
        </div>
      </div>
      
      <!-- 开始检测按钮 -->
      <div class="detection-action">
        <el-button 
          type="primary" 
          @click="startDetection" 
          :loading="detectionResult.loading"
          class="detection-button"
        >
          开始检测
        </el-button>
      </div>
      
      <!-- 数据描述 -->
      <div class="section">
        <h2 class="section-title">数据概述</h2>
        
        <div class="data-overview-cards">
          <div class="data-overview-card">
            <div class="overview-title">总记录数</div>
            <div class="overview-value">{{ datasetInfo.test.dataCount }}</div>
          </div>
          
          <div class="data-overview-card">
            <div class="overview-title">攻击类型数</div>
            <div class="overview-value">{{ datasetInfo.test.classCount }}</div>
          </div>
          
          <div class="data-overview-card">
            <div class="overview-title">正常流量占比</div>
            <div class="overview-value" :style="{color: '#43a1ff'}">{{ normalTrafficPercentage }}</div>
          </div>
          
          <div class="data-overview-card">
            <div class="overview-title">攻击流量占比</div>
            <div class="overview-value" :style="{color: '#5470c6'}">{{ attackTrafficPercentage }}</div>
          </div>
        </div>
      </div>
      
      <!-- 检测结果 -->
      <div class="section">
        <h2 class="section-title">检测结果</h2>
        <div class="result-cards">
          <div class="result-card">
            <div class="result-title">准确率</div>
            <div class="result-value">{{ detectionResult.accuracy }}</div>
          </div>
          <div class="result-card">
            <div class="result-title">召回率</div>
            <div class="result-value">{{ detectionResult.recall }}</div>
          </div>
          <div class="result-card">
            <div class="result-title">损失率</div>
            <div class="result-value">{{ detectionResult.loss }}</div>
          </div>
        </div>
      </div>
      
      <!-- 数据统计图表 -->
      <div class="charts-section">
        <h2 class="section-title">数据统计</h2>
        <div class="charts-row">
          <div class="chart-card">
            <h3 class="chart-title">流量分布</h3>
            <div class="chart-container" ref="trafficChartRef"></div>
          </div>
          <div class="chart-card">
            <h3 class="chart-title">攻击类型分布</h3>
            <div class="chart-container" ref="attackChartRef"></div>
          </div>
        </div>
        <div class="charts-row">
          <div class="chart-card">
            <h3 class="chart-title">协议类型统计</h3>
            <div class="chart-container" ref="protocolChartRef"></div>
          </div>
          <div class="chart-card">
            <h3 class="chart-title">流量波动</h3>
            <div class="chart-container" ref="trendChartRef"></div>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, reactive, onUnmounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Monitor, Timer, DataAnalysis, Upload, Document, Close } from '@element-plus/icons-vue'
  import * as echarts from 'echarts'
  import { 
    getAlgorithms, 
    uploadDataset, 
    runModelPrediction,
    getLatestResult
  } from '../../api/detection'
  
  // 响应式数据
  // 图表引用
  const trafficChartRef = ref(null)
  const protocolChartRef = ref(null)
  const attackChartRef = ref(null)
  const trendChartRef = ref(null)
  
  // 攻击类型ID到名称的映射表
  const attackIdToType = {
    0: 'normal',      // 正常流量
    1: 'neptune',     // DoS攻击
    2: 'buffer_overflow',
    3: 'mscan',
    4: 'guess_passwd',
    5: 'smurf',
    6: 'pod',
    7: 'teardrop',
    8: 'land',
    9: 'back',
    10: 'apache2',
    11: 'snmpgetattack',
    12: 'httptunnel',
    13: 'worm',
    14: 'portsweep',
    15: 'ipsweep',
    16: 'mailbomb',
    17: 'satan',
    18: 'nmap',
    19: 'xterm',
    20: 'processtable',
    21: 'udpstorm'
  }

  // 攻击类型到类别的映射表
  const attackTypeToCategory = {
    'neptune': 'DoS',
    'normal': 'Normal',
    'buffer_overflow': 'U2R',
    'mscan': 'Probe',
    'guess_passwd': 'R2L',
    'smurf': 'DoS',
    'pod': 'DoS',
    'teardrop': 'DoS',
    'land': 'DoS',
    'back': 'DoS',
    'apache2': 'DoS',
    'snmpgetattack': 'R2L',
    'httptunnel': 'U2R',
    'worm': 'R2L',
    'portsweep': 'Probe',
    'ipsweep': 'Probe',
    'mailbomb': 'DoS',
    'satan': 'Probe',
    'nmap': 'Probe',
    'xterm': 'U2R',
    'processtable': 'DoS',
    'udpstorm': 'DoS',
    'default': '其他'
  }

  // 攻击类别说明
  const attackCategories = {
    'DoS': 'DoS',
    'Probe': 'Probe',
    'R2L': 'R2L',
    'U2R': 'U2R',
    'Normal': '其他',
    'default': '其他'
  }
  
  // 文件上传相关
  const fileInput = ref(null)
  const selectedFile = ref(null)
  const uploading = ref(false)
  const uploadSuccess = ref(false)
  
  // 流量占比数据
  const normalTrafficPercentage = ref('0.0%')
  const attackTrafficPercentage = ref('0.0%')
  
  // 选择的算法
  const selectedAlgorithm = ref('cnn')
  const algorithmMapping = {
    'cnn': 'CNN',
    'lstm': 'LSTM',
    'hybrid': 'CNN+LSTM'
  }
  
  // 数据集信息
  const datasetInfo = reactive({
    test: {
      dataCount: 0,
      featureCount: 0,
      classCount: 0
    },
    train: {
      dataCount: 0,
      featureCount: 0,
      classCount: 0
    }
  })
  
  // 检测结果
  const detectionResult = reactive({
    accuracy: '0.0%',
    recall: '0.0%',
    loss: '0.0',
    loading: false,
    hasResult: false
  })
  
  // 图表实例管理
  const chartInstances = {
    traffic: null,
    protocol: null,
    attack: null,
    trend: null
  }
  
  // 处理销毁和清理图表实例
  const disposeChart = (chartRef) => {
    if (chartRef && chartRef.value) {
      const dom = chartRef.value
      // 检查dom元素上是否有echarts实例
      const existingInstance = echarts.getInstanceByDom(dom)
      if (existingInstance) {
        existingInstance.dispose()
      }
    }
  }
  
  // 选择算法
  const selectAlgorithm = (algorithm) => {
    selectedAlgorithm.value = algorithm
    ElMessage.success(`已选择 ${algorithmMapping[algorithm]} 算法`)
  }
  
  // 触发文件选择
  const triggerFileUpload = () => {
    fileInput.value.click()
  }
  
  // 文件选择变更处理
  const handleFileChange = (event) => {
    const files = event.target.files
    if (files && files.length > 0) {
      selectedFile.value = files[0]
      uploadFile(files[0])
    }
  }
  
  // 上传文件
  const uploadFile = async (file) => {
    // 创建FormData对象
    const formData = new FormData()
    formData.append('file', file)
    formData.append('name', file.name)
    
    uploading.value = true
    uploadSuccess.value = false
    
    try {
      const response = await uploadDataset(formData)
      
      if (response.code === 20000) {
        ElMessage.success('文件上传成功!')
        uploadSuccess.value = true
        
        // 更新数据统计信息
        datasetInfo.test.dataCount = response.data.record_count || 10000
        datasetInfo.test.featureCount = response.data.feature_count || 41
        datasetInfo.test.classCount = response.data.class_count || 5
        
        // 训练集和测试集信息相同（可以根据实际情况调整）
        datasetInfo.train = { ...datasetInfo.test }
        
        // 设置默认的流量占比数据
        normalTrafficPercentage.value = '0.0%'
        attackTrafficPercentage.value = '0.0%'
      } else {
        ElMessage.error(response.message || '上传失败')
      }
    } catch (error) {
      ElMessage.error('文件上传失败，请重试')
      console.error('上传错误:', error)
    } finally {
      uploading.value = false
    }
  }
  
  // 清除已选择的文件
  const clearSelectedFile = () => {
    selectedFile.value = null
    uploadSuccess.value = false
    if (fileInput.value) {
      fileInput.value.value = ''
    }
  }
  
  // 开始检测
  const startDetection = async () => {
    if (!selectedFile.value) {
      ElMessage.warning('请先上传数据集')
      return
    }

    // 显示提示弹窗
    await ElMessageBox.confirm(
      '检测过程可能需要较长时间（约1-2分钟），请耐心等待。',
      '开始检测',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'info'
      }
    ).catch(() => {
      return Promise.reject('用户取消')
    })
    
    try {
      detectionResult.loading = true
      
      // 执行模型预测
      const modelType = algorithmMapping[selectedAlgorithm.value]
      const result = await runModelPrediction(modelType, selectedFile.value)
      
      if (result.code === 20000) {
        // 提取数据并设置默认值
        const accuracy = result.data.prediction_info?.evaluation?.accuracy ?? 0;
        const recall = result.data.prediction_info?.evaluation?.recall ?? 0;
        const loss = result.data.prediction_info?.evaluation?.loss ?? 0;
        
        // 更新检测结果
        detectionResult.accuracy = `${(accuracy * 100).toFixed(1)}%`
        detectionResult.recall = `${(recall * 100).toFixed(1)}%`
        detectionResult.loss = loss.toString().includes('.') ? loss.toFixed(2) : '0.00'
        detectionResult.hasResult = true
        
        // 获取流量占比数据
        const normalPercent = result.data.prediction_info?.normal_traffic_percentage ?? 0;
        const attackPercent = result.data.prediction_info?.attack_traffic_percentage ?? 0;
        
        // 更新流量占比数据
        normalTrafficPercentage.value = `${(normalPercent).toFixed(1)}%`;
        attackTrafficPercentage.value = `${(attackPercent).toFixed(1)}%`;
        
        ElMessage.success('检测完成!')
        
        // 准备图表数据
        const chartData = {
          // 使用后端返回的应用层协议数据
          traffic_data: result.data.prediction_info?.protocol_distribution?.application_layer ? 
            [
              result.data.prediction_info.protocol_distribution.application_layer.HTTP || 0,
              result.data.prediction_info.protocol_distribution.application_layer.HTTPS || 0,
              result.data.prediction_info.protocol_distribution.application_layer.FTP || 0,
              result.data.prediction_info.protocol_distribution.application_layer.SSH || 0,
              result.data.prediction_info.protocol_distribution.application_layer.DNS || 0
            ] : [0, 0, 0, 0, 0], // 如果没有数据则使用默认值
          
          // 使用后端返回的传输层协议数据
          protocol_distribution: result.data.prediction_info?.protocol_distribution?.transport_layer ? 
            result.data.prediction_info.protocol_distribution.transport_layer : 
            {
              TCP: 0,
              UDP: 0,
              ICMP: 0,
              Other: 0
            },
          
          // 处理攻击类型分布数据 - 将对象转换为图表所需的格式
          attack_data: result.data.prediction_info?.class_distribution ? 
            Object.entries(result.data.prediction_info.class_distribution).map(([key, value]) => {
              return {
                name: key,
                value: value
              };
            }) : [{name: 'default', value: 100}],
          trend_data: result.data.sample_predictions || null
        }
        
        // 刷新图表
        refreshCharts(chartData)
      } else {
        ElMessage.error(result.message || '检测失败')
      }
    } catch (error) {
      ElMessage.error('检测执行失败，请重试')
      console.error('检测错误:', error)
    } finally {
      detectionResult.loading = false
    }
  }
  
  // 刷新图表数据
  const refreshCharts = (data) => {
    // 确保data是一个对象
    const safeData = data || {};
    
    // 更新图表数据
    if (safeData.traffic_data) initTrafficChart(safeData.traffic_data);
    
    // 为协议类型图表准备正确的数据格式
    if (safeData.protocol_distribution) {
      // 检查是否是嵌套结构（包含transport_layer）
      if (safeData.protocol_distribution.transport_layer) {
        // 如果是嵌套结构，从transport_layer中提取数据
        const transportLayer = safeData.protocol_distribution.transport_layer;
        const protocolData = [
          { value: transportLayer.TCP || 0, name: 'TCP' },
          { value: transportLayer.UDP || 0, name: 'UDP' },
          { value: transportLayer.ICMP || 0, name: 'ICMP' },
          { value: transportLayer.Other || 0, name: '其他' }
        ];
        initProtocolChart(protocolData);
      } else {
        // 如果是扁平结构，直接使用
        const protocolData = [
          { value: safeData.protocol_distribution.TCP || 0, name: 'TCP' },
          { value: safeData.protocol_distribution.UDP || 0, name: 'UDP' },
          { value: safeData.protocol_distribution.ICMP || 0, name: 'ICMP' },
          { value: safeData.protocol_distribution.Other || 0, name: '其他' }
        ];
        initProtocolChart(protocolData);
      }
    } else {
      // 如果没有协议分布数据，使用默认数据
      initProtocolChart();
    }
    
    if (safeData.attack_data) initAttackChart(safeData.attack_data);
    if (safeData.trend_data) initTrendChart(safeData.trend_data);
  }
  
  // 获取最新的预测结果
  const getLastResult = async () => {
    try {
      const result = await getLatestResult()
      if (result.code === 20000 && result.data) {
        // 提取数据并设置默认值
        const accuracy = result.data.accuracy !== undefined ? result.data.accuracy : 0;
        const recall = result.data.recall_score !== undefined ? result.data.recall_score : 0;
        const loss = result.data.loss !== undefined ? result.data.loss : 0;
        
        // 更新检测结果
        detectionResult.accuracy = `${(accuracy * 100).toFixed(1)}%`
        detectionResult.recall = `${(recall * 100).toFixed(1)}%`
        detectionResult.loss = loss.toString().includes('.') ? loss.toFixed(2) : '0.00'
        detectionResult.hasResult = true
        
        // 获取流量占比数据
        const normalPercent = result.data.normal_traffic_percentage ?? 0;
        const attackPercent = result.data.attack_traffic_percentage ?? 0;
        
        // 更新流量占比数据
        normalTrafficPercentage.value = `${(normalPercent).toFixed(1)}%`;
        attackTrafficPercentage.value = `${(attackPercent).toFixed(1)}%`;
        
        // 准备图表数据，确保协议类型数据正确
        const chartData = {
          // 使用后端返回的应用层协议数据
          traffic_data: result.data.protocol_distribution?.application_layer ? 
            [
              result.data.protocol_distribution.application_layer.HTTP || 0,
              result.data.protocol_distribution.application_layer.HTTPS || 0,
              result.data.protocol_distribution.application_layer.FTP || 0,
              result.data.protocol_distribution.application_layer.SSH || 0,
              result.data.protocol_distribution.application_layer.DNS || 0
            ] : [0, 0, 0, 0, 0], // 如果没有数据则使用默认值
          
          // 使用后端返回的传输层协议数据
          protocol_distribution: result.data.protocol_distribution?.transport_layer ? 
            result.data.protocol_distribution.transport_layer : 
            {
              TCP: 0,
              UDP: 0,
              ICMP: 0,
              Other: 0
            },
          
          // 其他图表数据 - 确保攻击分布数据格式正确
          attack_data: result.data.attack_distribution ? 
            (Array.isArray(result.data.attack_distribution) ? 
              // 如果是数组但没有name属性，转换为对象格式
              result.data.attack_distribution.map((value, index) => {
                if (typeof value === 'object' && value.name) return value;
                const attackType = Object.keys(attackTypeNames)[index] || 'default';
                return { name: attackType, value: value };
              }) : 
              // 如果是对象，转换为数组格式
              Object.entries(result.data.attack_distribution).map(([key, value]) => {
                return { name: key, value: value };
              })
            ) : [],
          trend_data: result.data.sample_predictions || null
        }
        
        // 刷新图表数据
        refreshCharts(chartData)
      }
    } catch (error) {
      console.error('获取最新结果失败:', error)
    }
  }
  
  // 初始化图表
  onMounted(() => {
    // 尝试获取最新的预测结果
    getLastResult()
    
    // 初始化图表
    initTrafficChart()
    initProtocolChart()
    initAttackChart()
    initTrendChart()
  })
  
  // 初始化流量分析柱状图
  const initTrafficChart = (data) => {
    // 销毁已有实例
    disposeChart(trafficChartRef)
    
    // 初始化新实例
    const chartInstance = echarts.init(trafficChartRef.value)
    chartInstances.traffic = chartInstance
    
    // 默认数据全部设为0
    const defaultData = [0, 0, 0, 0, 0]
    
    // 安全获取图表数据
    let chartData = defaultData
    if (Array.isArray(data)) {
      // 确保数据长度为5，不足的补0
      chartData = data.slice(0, 5).map(value => value || 0)
      while (chartData.length < 5) {
        chartData.push(0)
      }
    }
    
    const option = {
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['HTTP', 'HTTPS', 'FTP', 'SSH', 'DNS'],
        axisLine: {
          lineStyle: {
            color: '#999'
          }
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: false
        },
        splitLine: {
          lineStyle: {
            color: '#eee'
          }
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      series: [
        {
          data: chartData,
          type: 'bar',
          itemStyle: {
            color: '#0080ff'
          }
        }
      ]
    }
    
    chartInstance.setOption(option)
    
    // 窗口大小变化时重新调整图表
    const resizeHandler = () => {
      if (chartInstances.traffic) {
        chartInstances.traffic.resize()
      }
    }
    
    window.addEventListener('resize', resizeHandler)
    
    return chartInstance
  }
  
  // 初始化协议类型分布环形图
  const initProtocolChart = (data) => {
    // 销毁已有实例
    disposeChart(protocolChartRef)
    
    // 初始化新实例
    const chartInstance = echarts.init(protocolChartRef.value)
    chartInstances.protocol = chartInstance
    
    // 提供默认数据 - 所有值默认为0
    const defaultData = [
      { value: 0, name: 'TCP' },
      { value: 0, name: 'UDP' },
      { value: 0, name: 'ICMP' },
      { value: 0, name: '其他' }
    ];
    
    // 如果传入数据是数组并且有内容，使用传入数据，否则使用默认数据
    let chartData = defaultData;
    if (Array.isArray(data)) {
      // 创建一个映射来存储每个协议的值
      const protocolMap = {
        TCP: 0,
        UDP: 0,
        ICMP: 0,
        '其他': 0
      };
      
      // 遍历数据并更新映射
      data.forEach(item => {
        if (item && item.name && protocolMap.hasOwnProperty(item.name)) {
          protocolMap[item.name] = item.value || 0;
        }
      });
      
      // 将映射转换为图表数据格式
      chartData = Object.entries(protocolMap).map(([name, value]) => ({
        name,
        value
      }));
    }
    
    const option = {
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'category',
        data: chartData.map(item => item.name),
        axisLine: {
          lineStyle: {
            color: '#999'
          }
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: false
        },
        splitLine: {
          lineStyle: {
            color: '#eee'
          }
        }
      },
      series: [
        {
          name: '协议类型',
          type: 'bar',
          data: chartData.map(item => item.value),
          itemStyle: {
            color: '#0080ff'
          },
          label: {
            show: false
          }
        }
      ]
    }
    
    chartInstance.setOption(option)
    
    // 窗口大小变化时重新调整图表
    const resizeHandler = () => {
      if (chartInstances.protocol) {
        chartInstances.protocol.resize()
      }
    }
    
    window.addEventListener('resize', resizeHandler)
    
    return chartInstance
  }
  
  // 初始化攻击类型统计环形图
  const initAttackChart = (data) => {
    // 销毁已有实例
    disposeChart(attackChartRef)
    
    // 初始化新实例
    const chartInstance = echarts.init(attackChartRef.value)
    chartInstances.attack = chartInstance
    
    // 颜色列表
    const colorList = {
      'DoS': '#0080ff',
      'Probe': '#91cc75',
      'R2L': '#fac858',
      'U2R': '#ee6666',
      'Normal': '#73c0de',
      'default': '#3ba272'
    }
    
    // 默认数据 - 所有值默认为0
    const defaultData = [
      { value: 0, name: 'DoS', category: 'DoS' },
      { value: 0, name: '探测攻击', category: 'Probe' },
      { value: 0, name: '远程渗透', category: 'R2L' },
      { value: 0, name: '权限提升', category: 'U2R' },
      { value: 0, name: '正常流量', category: 'Normal' },
      { value: 0, name: '其他', category: 'default' }
    ]
    
    // 安全获取图表数据并按类别聚合
    let chartData = defaultData
    if (Array.isArray(data) && data.length > 0) {
      // 创建类别数据映射
      const categoryData = {}
      
      // 遍历数据并按类别聚合
      data.forEach(item => {
        // 将数字ID转换为攻击类型名称
        let attackType;
        if (typeof item.name === 'number') {
          attackType = attackIdToType[item.name];
        } else if (typeof item.name === 'string' && /^\d+$/.test(item.name)) {
          // 处理字符串形式的数字ID
          attackType = attackIdToType[parseInt(item.name)];
        } else {
          attackType = item.name;
        }
        
        // 确保有默认值
        attackType = attackType || 'default';
        
        // 将攻击类型名称映射到攻击类别
        const category = attackTypeToCategory[attackType] || 'default';
        const categoryName = attackCategories[category] || attackCategories['default']
        
        if (!categoryData[category]) {
          categoryData[category] = {
            value: 0,
            name: categoryName,
            category: category,
            itemStyle: { color: colorList[category] }
          }
        }
        categoryData[category].value += (item.value || 0)
      })
      
      // 转换为数组格式
      chartData = Object.values(categoryData)
    } else {
      // 如果没有数据，使用默认数据并添加颜色
      chartData = defaultData.map(item => ({
        ...item,
        itemStyle: { color: colorList[item.category] }
      }))
    }
    
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        textStyle: {
          color: '#666'
        }
      },
      series: [
        {
          name: '攻击类型',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            position: 'outside',
            formatter: '{b}\n{c}',
            fontSize: 12,
            color: '#333'
          },
          labelLine: {
            show: true,
            length: 10,
            length2: 10,
            smooth: true,
            lineStyle: {
              color: '#999'
            }
          },
          data: chartData
        }
      ]
    }
    
    chartInstance.setOption(option)
    
    // 窗口大小变化时重新调整图表
    const resizeHandler = () => {
      if (chartInstances.attack) {
        chartInstances.attack.resize()
      }
    }
    
    window.addEventListener('resize', resizeHandler)
    
    return chartInstance
  }
  
  // 初始化流量趋势折线图
  const initTrendChart = (data) => {
    // 销毁已有实例
    disposeChart(trendChartRef)
    
    // 初始化新实例
    const chartInstance = echarts.init(trendChartRef.value)
    chartInstances.trend = chartInstance
    
    // 生成默认数据，全部为0
    const generateData = () => {
      return Array(10).fill(0) // 返回10个0值的数组
    }
    
    // 安全获取图表数据
    let chartData = generateData()
    if (Array.isArray(data) && data.length > 0) {
      // 确保数据长度为10，不足的补0
      chartData = data.slice(-10).map(value => value || 0)
      while (chartData.length < 10) {
        chartData.unshift(0)
      }
    }
    
    // 创建时间标签，使用更合理的时间格式
    const now = new Date()
    const dateLabels = Array.from({length: 10}, (_, i) => { // 固定为10个数据点
      const date = new Date(now.getTime() - (9 - i) * 60 * 1000) // 从当前时间往前推10分钟
      return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    })
    
    const option = {
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'line',
          lineStyle: {
            color: '#0080ff',
            width: 1,
            type: 'solid'
          }
        },
        formatter: function(params) {
          const data = params[0];
          return `时间：${data.name}<br/>流量值：${data.value}`;
        }
      },
      xAxis: {
        type: 'category',
        data: dateLabels,
        axisLine: {
          lineStyle: {
            color: '#999'
          }
        },
        axisLabel: {
          formatter: '{value}'
          // 如果标签太密集，可以启用旋转
          // rotate: 45
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: false
        },
        splitLine: {
          lineStyle: {
            color: '#eee'
          }
        }
      },
      series: [
        {
          data: chartData,
          type: 'line',
          smooth: true,
          itemStyle: {
            color: '#0080ff'
          },
          lineStyle: {
            width: 3
          }
        }
      ]
    }
    
    chartInstance.setOption(option)
    
    // 窗口大小变化时重新调整图表
    const resizeHandler = () => {
      if (chartInstances.trend) {
        chartInstances.trend.resize()
      }
    }
    
    window.addEventListener('resize', resizeHandler)
    
    return chartInstance
  }
  
  // 清理函数，销毁所有图表实例
  const cleanupCharts = () => {
    Object.values(chartInstances).forEach(instance => {
      if (instance) {
        instance.dispose()
      }
    })
    
    // 重置图表实例
    chartInstances.traffic = null
    chartInstances.protocol = null
    chartInstances.attack = null
    chartInstances.trend = null
  }
  
  // 组件销毁时清理资源
  onUnmounted(() => {
    // 清理图表实例
    cleanupCharts()
    
    // 移除事件监听器
    window.removeEventListener('resize', () => {})
  })
  </script>
  
  <style scoped>
  .dashboard-container {
    padding: 20px;
    background-color: #f5f7fa;
  }
  
  .section {
    margin-bottom: 30px;
  }
  
  .section-title {
    font-size: 16px;
    margin-bottom: 20px;
    color: #333;
  }
  
  /* 算法选择 */
  .algorithm-cards {
    display: flex;
    gap: 20px;
  }
  
  .algorithm-card {
    flex: 1;
    display: flex;
    align-items: center;
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s;
    border: 1px solid #e8e8e8;
  }
  
  .algorithm-card.active {
    border-color: #0080ff;
  }
  
  .algorithm-icon {
    font-size: 30px;
    color: #0080ff;
    margin-right: 15px;
  }
  
  .algorithm-name {
    font-weight: 500;
    margin-bottom: 4px;
  }
  
  .algorithm-desc {
    font-size: 12px;
    color: #999;
  }
  
  /* 上传区 */
  .upload-section {
    margin: 20px 0;
  }
  
  .upload-box {
    background-color: #f9fbff;
    border: 2px dashed #a0cfff;
    border-radius: 10px;
    padding: 30px 20px;
    text-align: center;
    transition: all 0.3s;
  }
  
  .upload-box:hover {
    border-color: #409eff;
    background-color: #f5f9ff;
  }
  
  .upload-icon {
    font-size: 50px;
    color: #409eff;
    margin-bottom: 15px;
  }
  
  .upload-title {
    font-size: 20px;
    font-weight: 500;
    color: #333;
    margin-bottom: 10px;
  }
  
  .upload-desc {
    color: #666;
    margin-bottom: 5px;
    font-size: 14px;
  }
  
  .upload-button {
    margin-top: 20px;
    padding: 12px 25px;
    font-size: 16px;
  }
  
  .selected-file {
    display: flex;
    align-items: center;
    margin-top: 15px;
    padding: 10px;
    background: #edf6ff;
    border-radius: 6px;
    color: #444;
    font-size: 14px;
  }
  
  .selected-file .el-icon {
    margin-right: 8px;
    color: #409eff;
  }
  
  .selected-file .remove-icon {
    margin-left: auto;
    cursor: pointer;
    color: #999;
  }
  
  .selected-file .remove-icon:hover {
    color: #f56c6c;
  }
  
  /* 数据概述卡片 */
  .data-overview-cards {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
  }
  
  .data-overview-card {
    flex: 1;
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    text-align: center;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
    display: flex;
    flex-direction: column;
    justify-content: center;
    min-height: 120px;
  }
  
  .overview-title {
    color: #666;
    font-size: 14px;
    margin-bottom: 10px;
  }
  
  .overview-value {
    font-size: 24px;
    font-weight: 500;
    color: #0080ff;
  }
  
  @media (max-width: 768px) {
    .data-overview-cards {
      flex-direction: column;
      gap: 10px;
    }
    
    .data-overview-card {
      min-height: auto;
      padding: 15px;
    }
  }
  
  .detection-action {
    display: flex;
    justify-content: flex-end;
    margin: 20px 0;
  }

  .detection-button {
    padding: 12px 24px;
    font-size: 16px;
  }
  
  /* 检测结果 */
  .result-cards {
    display: flex;
    gap: 20px;
  }
  
  .result-card {
    flex: 1;
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    text-align: center;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
  }
  
  .result-title {
    color: #999;
    margin-bottom: 10px;
  }
  
  .result-value {
    font-size: 24px;
    font-weight: 500;
    color: #0080ff;
  }
  
  /* 图表样式 */
  .charts-section {
    margin-bottom: 30px;
  }
  
  .charts-row {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
  }
  
  .chart-card {
    flex: 1;
    background-color: #fff;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
  }
  
  .chart-title {
    font-size: 16px;
    margin: 0 0 15px 0;
    color: #333;
  }
  
  .chart-container {
    height: 300px;
    width: 100%;
  }
  
  /* 响应式处理 */
  @media (max-width: 992px) {
    .charts-row {
      flex-direction: column;
    }
  }
  </style>